<?php defined('SYSPATH') or die('No direct script access.');

/**
 *退件包裹质检处理界面
 * @package  qcwo
 * @author   taj
 */
class Controller_Returnedparcelsort extends Controller_Admin
{
    /**
     *退件处理权限
     */
    public function before()
    {
        try{
            ACL::Required('update returnedparcel');
        }catch(HTTP_Exception_403 $e){
            Message::error('sorry，你没有权限进这个目录');
            $this->request->redirect(URL::base(TRUE));
        }
        parent::before();
    }

    /**
     *退件默认界面
     */
    public function action_index()
    {
        $this->title = __('退件接收单待处理');
        $batches     = basic::get_batches();//批次号文本框提示语


        
        $ops = array();
        $op  = array();
        if(isset($_POST['select_pi'])){
            if($_POST['select_pi']==''){
                Message::error('输入的批次号不能为空！');
            }else{

                $batch = ORM::factory('returned_batch')
                    ->where('batch_code','=',$_POST['select_pi'])
                    ->find();
                if($batch->id==''){
                    Message::error('输入的批次号不存在，请输入正确的批次号！');
                }else{


                    $parcels = ORM::factory('returned_parcel')
                        ->where('returned_batch_code','=',$_POST['select_pi'])
                        ->order_by('created','DESC')
                        ->find_all();
                    foreach($parcels as $parcel){
                        $op['returned_id']          = $parcel->id;
                        $op['erp_orders_id']        = $parcel->erp_order_id;
                        $op['ebay_order_id']        = $parcel->ebay_orders_id;
                        $op['shipping_method']      = $parcel->shipping_method;
                        $op['orders_shipping_code'] = $parcel->orders_shipping_code;
                        $op['saomiao_time']         = $parcel->created;
                        $user                       = ORM::factory('user',$parcel->userid);
                        $op['saomiao_user']         = $user->nick;
                        $op['sku']                  = $parcel->sku;
                        $op['sku_name']             = $parcel->sku_name;
                        $op['sku_storage_position'] = $parcel->storage_position;
                        $op['sku_num']              = $parcel->num;
                        $op['qualified_num']        = $parcel->qualified_num;
                        $op['failure_num']          = $parcel->failure_num;
                        $op['status']               = $parcel->status;
                        $op['qc_user']              = $parcel->qc_user;
                        $op['qc_time']              = $parcel->qc_time;

                        $undefine = ORM::factory('unqualified_deal_invoice')
                            ->where('returned_parcel_id','=',$parcel->id)
                            ->find();
                        if($undefine->id==''){
                            $op['error_remark'] = '';
                        }else{

                            $op['error_remark'] = $undefine->quality_remark;
                        }

                        $ops[] = $op;
                    }
                    if(empty($ops)){
                        Message::error('此批次号查询结果为空！');
                    }
                }
            }
        }

        $view = View::factory('inventory/returnedparcelsort')
            ->set('batches',$batches)
            ->set('ops',$ops)
            ->set('select_pi',isset($_POST['select_pi'])?$_POST['select_pi']:'');

        $this->response->body($view);
    }

    public function action_update_parcel()
    {
        //加载仓库配置信息--begin --
        $warehouseid = Kohana::$config->load('warehouse')->warehouse_id;
        //---end--
        $returned_id = isset($_POST['returned_id'])?$_POST['returned_id']:0;
        $hege_num    = isset($_POST['hege_num'])?trim($_POST['hege_num']):0;
        $error_num   = isset($_POST['error_num'])?trim($_POST['error_num']):0;
        $notice      = isset($_POST['notice'])?$_POST['notice']:0;
        //	$hege_remark = isset($_POST['hege_remark'])?trim($_POST['hege_remark']):'';
        $error_remark = isset($_POST['error_remark'])?trim($_POST['error_remark']):'';
        $user         = ORM::factory('user',User::active_user()->id);

        if($notice==20){//新增不合格和合格量记录

            $update_parcels = ORM::factory('returnedparcel')
                ->where('id','=',$returned_id)
                ->find();
            if($update_parcels->status==0){
                $update_parcels->qc_user       = User::active_user()->id;
                $update_parcels->qc_time       = date('Y-m-d H:i:s');
                $update_parcels->qualified_num = $hege_num;
                $update_parcels->failure_num   = $error_num;
                $update_parcels->status        = 20;
                $update_parcels->warehouseid   = $warehouseid;
                $update_parcels->save();

                $insert_wo = ORM::factory('warehouseorder');
                if($hege_num>0){
                    $insert_wo->warehouseid        = $warehouseid;
                    $insert_wo->warehouse_date     = date('Y-m-d H:i:s');
                    $insert_wo->op_time            = date('Y-m-d H:i:s');
                    $insert_wo->returned_parcel_id = $returned_id;
                    $insert_wo->sku                = $update_parcels->sku;
                    $insert_wo->sku_name           = $update_parcels->sku_name;
                    $insert_wo->storage_position   = $update_parcels->storage_position;
                    $insert_wo->warehouse_quantity = $hege_num;
                    $insert_wo->remark             = $error_remark.',订单退件入库，订单号是'.$update_parcels->erp_order_id;
                    $insert_wo->type               = 20;
                    $insert_wo->warehouse_man      = User::active_user()->id;
                    $insert_wo->single_price       = $update_parcels->single_price;
                    $insert_wo->money              = $update_parcels->single_price*$hege_num;
                    $insert_wo->cost               = $update_parcels->single_price*$hege_num;
                    $insert_wo->warehouseid        = $warehouseid;

                    $insert_wo->save();
                }

                $insert_unqualified = ORM::factory('unqualified');
                if($error_num>0){
                    $insert_unqualified->warehouseid        = $warehouseid;
                    $insert_unqualified->invoice_date       = date('Y-m-d H:i:s');
                    $insert_unqualified->returned_parcel_id = $returned_id;
                    $insert_unqualified->sku                = $update_parcels->sku;
                    $sku                                    = qualityaction::getskuname($update_parcels->sku);
                    $name                                   = qualityaction::geterpname($sku['oper']);
                    $userid                                 = qualityaction::getuserid($name);
                    $insert_unqualified->purchase_man       = $userid;
                    $insert_unqualified->sku_name           = $update_parcels->sku_name;
                    $insert_unqualified->quantity           = $error_num;
                    $insert_unqualified->status             = 10;
                    $insert_unqualified->check_time         = date('Y-m-d H:i:s');
                    $insert_unqualified->quality_man        = User::active_user()->id;
                    $insert_unqualified->quality_remark     = $error_remark.'，订单退件入不良品仓，退件订单号是'.$update_parcels->erp_order_id;
                    $insert_unqualified->save();
                }
                if($update_parcels->saved()&&($insert_wo->saved()||$insert_unqualified->saved())){

                    echo '保存成功!';
                }else{

                    echo '退件处理入库失败';
                }
            }else{

                echo '此条数据已处理，请不要重复提交';
            }
        }else{
            if($notice==10){//放弃对退件的处理，只记录时间及操作人，没有合格量及不合格量
                DB::update('returned_parcels')
                    ->set(array(
                        'qc_user' => User::active_user()->id,
                        'qc_time' => date('Y-m-d H:i:s'),
                        'status'  => 10
                    ))
                    ->where('id','=',$returned_id)
                    ->execute('newerp');
                echo '保存成功!';
            }else{

                echo '操作有问题';
            }
        }
    }

    public function action_test()
    {
        $sku      = 'LL1053';
        $supplier = new Service_Common();
        $result   = $supplier->get_sku_price($sku);
        echo $result;
    }

}
